package com.atguigu.gmall.cart.controller;

import com.atguigu.gmall.cart.service.CartInfoService;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.model.cart.CartInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author: 李旭
 * @create: 2021-09-07 11:21
 *
 *   加入购物车
 *   去购物车结算
 *
 *
 **/
@RestController
@RequestMapping("/api/cart")
public class CartInfoApiController {

    @Autowired
    private CartInfoService cartInfoService;

    //加入购物车
    @PostMapping("/addCart/{skuId}/{skuNum}")
    public void addCart(@PathVariable Long skuId, @PathVariable Integer skuNum
       , HttpServletRequest request){
        //真实用户ID
        String userId = AuthContextHolder.getUserId(request);
        if(StringUtils.isEmpty(userId)){
            //临时用户ID
            userId = AuthContextHolder.getUserTempId(request);
        }
   /*     System.out.println("userTempId:" + userTempId);
        System.out.println("userId:" + userId);*/
        cartInfoService.addCart(skuId,skuNum,userId);
    }
    //查询购物车
    @GetMapping("/findCartInfo/{skuId}")
    public CartInfo findCartInfo(@PathVariable Long skuId){

        return cartInfoService.findCartInfo(skuId);
    }
    //初始化加载购物车集合  http://api.gmall.com/api/cart/cartList
    @GetMapping("/cartList")
    public Result cartList(HttpServletRequest request){
        //入参： 真实用户ID  临时用户ID
        String userId = AuthContextHolder.getUserId(request);
        String userTempId = AuthContextHolder.getUserTempId(request);//逻辑开发 解决问题
        List<CartInfo> cartInfoList = cartInfoService.cartList(userId,userTempId);
        return Result.ok(cartInfoList);
    }
    //更新购物车的选中或取消状态
    @GetMapping("/checkCart/{skuId}/{isChecked}")
    public Result checkCart(@PathVariable Long skuId,@PathVariable Integer isChecked
      ,HttpServletRequest request){
        String userId = AuthContextHolder.getUserId(request);
        if(StringUtils.isEmpty(userId)){
            userId = AuthContextHolder.getUserTempId(request);
        }
        cartInfoService.checkCart(skuId,isChecked,userId);

        return Result.ok();
    }
    //查询购物车中已经选中了商品
    @GetMapping("/findCartInfoListByIsChecked")
    public List<CartInfo> findCartInfoListByIsChecked(HttpServletRequest request){
        String userId = AuthContextHolder.getUserId(request);
        return cartInfoService.findCartInfoListByIsChecked(userId);
    }
}
